package com.yygo.webapp.controller.material;

import com.yygo.Constants;
import com.yygo.model.LoanProduct;
import com.yygo.model.Material;
import com.yygo.model.MaterialAudit;
import com.yygo.model.User;
import com.yygo.model.enums.MaterialStatus;
import com.yygo.service.LoanProductManager;
import com.yygo.service.MaterialAuditManager;
import com.yygo.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.security.Principal;
import java.util.Date;
import java.util.List;

/**
 * Created by tiansha on 2015/10/31.
 */
@Controller
@RequestMapping("/auditMaterialsForm")
public class AuditMaterialsFormController extends BaseMaterialController {

    @Autowired
    private MaterialAuditManager materialAuditManager;

    @Autowired
    private LoanProductManager loanProductManager;

    @Autowired
    private UserManager userManager;

    @RequestMapping(method = RequestMethod.GET)
    public String audit(@RequestParam(required = true, value = "maId") Long maId,
                               Principal principal) {
        User loginUser = userManager.getUserByUsername(principal.getName());
        if (!loginUser.hasRole(Constants.Material_Audit_ROLE)) {
            throw new AccessDeniedException("You have no right to set material audit done");
        }
        MaterialAudit materialAudit = materialAuditManager.get(maId);
        materialAudit.setMaterialStatus(MaterialStatus.Printing);
        materialAuditManager.save(materialAudit);
        return "redirect:/materialAuditList";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String reject(@RequestParam(required = true, value = "maId") Long maId,
                        Principal principal) {
        User loginUser = userManager.getUserByUsername(principal.getName());
        if (!loginUser.hasRole(Constants.Material_Audit_ROLE)) {
            throw new AccessDeniedException("You have no right to reject material audit");
        }
        MaterialAudit materialAudit = materialAuditManager.get(maId);
        materialAudit.setMaterialStatus(MaterialStatus.Receiving);
        materialAudit.setAllReceived(false);
        materialAudit.getMaterialList().stream().forEach( material-> material.setReceived(false));
        materialAuditManager.save(materialAudit);
        return "redirect:/materialAuditList";
    }
}
